package org.jeecg.modules.charge.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.charge.entity.*;
import org.jeecg.modules.charge.service.IChargeInvoiceInhouseService;
import org.jeecg.modules.charge.service.IChargeInvoiceMangroupService;
import org.jeecg.modules.charge.service.IChargeInvoiceMangroupTypeService;
import org.jeecg.modules.charge.service.IChargeInvoiceTypeService;
import org.jeecg.modules.charge.service.impl.ChargeInvoiceInhouseServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 票据入库
 * @Author: jeecg-boot
 * @Date:   2019-08-08
 * @Version: V1.0
 */
@Slf4j
@Api(tags="票据入库")
@RestController
@RequestMapping("/b/charge/chargeInvoiceInhouse")
public class ChargeInvoiceInhouseController {
	@Autowired
	private IChargeInvoiceInhouseService chargeInvoiceInhouseService;

	@Autowired
	private IChargeInvoiceMangroupService chargeInvoiceMangroupService;

	@Autowired
	private IChargeInvoiceMangroupTypeService chargeInvoiceMangroupTypeService;

	@Autowired
	private IChargeInvoiceTypeService chargeInvoiceTypeService;

	 @Autowired
	 private ChargeInvoiceInhouseServiceImpl chargeInvoiceInhouseServiceImpl;

	
	/**
	  * 分页列表查询
	 * @param chargeInvoiceInhouse
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "票据入库-分页列表查询")
	@ApiOperation(value="票据入库-分页列表查询", notes="票据入库-分页列表查询")
	@GetMapping(value = "/lists")
	public Result<IPage<ChargeInvoiceInhouse>> queryPageList(ChargeInvoiceInhouse chargeInvoiceInhouse,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ChargeInvoiceInhouse>> result = new Result<IPage<ChargeInvoiceInhouse>>();
		if (chargeInvoiceInhouse.getGroupNo() != null){
			chargeInvoiceInhouse.setGroupNo("*"+chargeInvoiceInhouse.getGroupNo()+"*");
		}
		if (chargeInvoiceInhouse.getTypeName() != null){
			chargeInvoiceInhouse.setTypeName("*"+chargeInvoiceInhouse.getTypeName()+"*");
		}
		if (chargeInvoiceInhouse.getStartNum() != null){
			chargeInvoiceInhouse.setStartNum("*"+chargeInvoiceInhouse.getStartNum()+"*");
		}
		QueryWrapper<ChargeInvoiceInhouse> queryWrapper = QueryGenerator.initQueryWrapper(chargeInvoiceInhouse, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<ChargeInvoiceInhouse> page = new Page<ChargeInvoiceInhouse>(pageNo, pageSize);
		IPage<ChargeInvoiceInhouse> pageList = chargeInvoiceInhouseService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 首次加载不进行全查询
	  * @param chargeInvoiceInhouse
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "票据入库-查询")
	 @ApiOperation(value="票据入库-查询", notes="票据入库-查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<ChargeInvoiceInhouse>> list(ChargeInvoiceInhouse chargeInvoiceInhouse,
										  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
										  HttpServletRequest req) {
		 return null;
	 }

	 /**
	  * 选中票据领用数据
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "选中票据查询")
	 @ApiOperation(value="选中票据查询", notes="选中票据查询")
	 @GetMapping(value = "/listById")
	 public Result<List<ChargeInvoiceInhouse>> listById(@RequestParam(value = "id") String id){
		 Result<List<ChargeInvoiceInhouse>> result = new Result<>();
		 String[] strings = id.split(",");
		 List<ChargeInvoiceInhouse> listInhouses = (List<ChargeInvoiceInhouse>) chargeInvoiceInhouseService.listByIds(Arrays.asList(strings));
		 result.setResult(listInhouses);
		 result.setSuccess(true);
		 return result;
	 }

	 /**
	  * 分页列表查询
	  * @param chargeInvoiceInhouse
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "票据领用列表查询")
	 @ApiOperation(value="票据领用-分页列表查询", notes="票据领用-分页列表查询")
	 @GetMapping(value = "/listReceice")
	 public Result<IPage<ChargeInvoiceInhouse>> listReceice(ChargeInvoiceInhouse chargeInvoiceInhouse,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		 Result<IPage<ChargeInvoiceInhouse>> result = new Result<IPage<ChargeInvoiceInhouse>>();
		 if (chargeInvoiceInhouse.getGroupNo() != null){
			 chargeInvoiceInhouse.setGroupNo("*"+chargeInvoiceInhouse.getGroupNo()+"*");
		 }
		 if (chargeInvoiceInhouse.getTypeName() != null){
			 chargeInvoiceInhouse.setTypeName("*"+chargeInvoiceInhouse.getTypeName()+"*");
		 }
		 if (chargeInvoiceInhouse.getStartNum() != null){
			 chargeInvoiceInhouse.setStartNum("*"+chargeInvoiceInhouse.getStartNum()+"*");
		 }
		 QueryWrapper<ChargeInvoiceInhouse> queryWrapper = QueryGenerator.initQueryWrapper(chargeInvoiceInhouse, req.getParameterMap());
		 queryWrapper.eq("status","0");
		 Page<ChargeInvoiceInhouse> page = new Page<ChargeInvoiceInhouse>(pageNo, pageSize);
		 IPage<ChargeInvoiceInhouse> pageList = chargeInvoiceInhouseService.page(page, queryWrapper);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }
	 /**
	  * 计算票据领用金额
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "票据领用金额")
	 @ApiOperation(value="票据领用金额", notes="票据领用金额")
	 @GetMapping(value = "/allMoney")
	 public Result<ChargeInvoiceInhouse> allMoney(@RequestParam(value = "id") String id){
		 Result<ChargeInvoiceInhouse> result = new Result<>();
		 String[] strings = id.split(",");
		 List<ChargeInvoiceInhouse> listInhouses = (List<ChargeInvoiceInhouse>) chargeInvoiceInhouseService.listByIds(Arrays.asList(strings));
		 Double moeny = 0.00;
		 for (int i = 0; i < listInhouses.size(); i++) {
			 moeny += listInhouses.get(i).getMoney();
		 }
		 LoginUser sysUser = SsoUtil.getLoginUser();
		 ChargeInvoiceInhouse chargeInvoiceInhouse = new ChargeInvoiceInhouse();
		 chargeInvoiceInhouse.setMoney(moeny);
		 chargeInvoiceInhouse.setCreateBy(sysUser.getUsername());
		 System.out.println("金额"+chargeInvoiceInhouse);
		 result.setResult(chargeInvoiceInhouse);
		 result.setSuccess(true);
		 return result;
	 }

	 /**
	  * 票据管理组信息查询
	  * @return
	  */
	 @AutoLog(value = "列表查询")
	 @ApiOperation(value="列表查询", notes="列表查询")
	 @GetMapping(value = "/selectMangroup")
	 public Result<List<ChargeInvoiceMangroup>> selectMangroup(){
		 LoginUser loginUser = SsoUtil.getLoginUser();
		 Result<List<ChargeInvoiceMangroup>> result = new Result<>();
		 List<ChargeInvoiceMangroup> listMangroup = chargeInvoiceMangroupService.selectByLimit(loginUser.getId());
		 result.setResult(listMangroup);
		 result.setSuccess(true);
		 return result;
	 }


	 /**
	  * 票据类型查询
	  * @return
	  */
	 @AutoLog(value = "票据类型查询")
	 @ApiOperation(value="票据类型查询", notes="票据类型查询")
	 @GetMapping(value = "/selectPaperType")
	 public Result<List<ChargeInvoiceMangroupType>> selectPaperType(ChargeInvoiceMangroupType chargeInvoiceMangroupType){
		 String groupNum = chargeInvoiceMangroupType.getGroupNum();
		 Result<List<ChargeInvoiceMangroupType>> result = new Result<>();
		 List<ChargeInvoiceMangroupType> listMangroupType = chargeInvoiceMangroupTypeService.selectType(groupNum);
		 result.setResult(listMangroupType);
		 result.setSuccess(true);
		 return result;
	 }


	 /**
	  * 票据所有类型查询
	  * @return
	  */
	 @AutoLog(value = "票据类型查询")
	 @ApiOperation(value="票据类型查询", notes="票据类型查询")
	 @GetMapping(value = "/selectPaperTypeAll")
	 public Result<List<ChargeInvoiceType>> selectPaperTypeAll(){
		 Result<List<ChargeInvoiceType>> result = new Result<>();
		 List<ChargeInvoiceType> listype = chargeInvoiceInhouseService.selectTypeAll();
		 result.setResult(listype);
		 result.setSuccess(true);
		 return result;
	 }

	/**
	  *   添加
	 * @param chargeInvoiceInhouse
	 * @return
	 */
	@AutoLog(value = "票据入库-添加")
	@ApiOperation(value="票据入库-添加", notes="票据入库-添加")
	@PostMapping(value = "/add")
	public Result<ChargeInvoiceInhouse> add(@RequestBody ChargeInvoiceInhouse chargeInvoiceInhouse) {
		Result<ChargeInvoiceInhouse> result = new Result<ChargeInvoiceInhouse>();
		try {
			ChargeInvoiceType chargeInvoiceType = chargeInvoiceTypeService.selectByTypenum(chargeInvoiceInhouse.getTypeNum());//查询类型编号对应类型名
			String startNum = chargeInvoiceInhouse.getStartNum();
			Integer length = startNum.length();

			//拼接票据起始编号
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < length; i++) {
				stringBuilder.append("0");
			}
			DecimalFormat df = new DecimalFormat(stringBuilder.toString());
			Integer manynum = Integer.valueOf(chargeInvoiceInhouse.getMany());
			Integer newstartnum = Integer.parseInt(startNum);
			String group = chargeInvoiceInhouse.getWord();
			Integer nstartnum = 0;
			Integer newendnum = 0;
            Double money=0.00;//每本金额
            Integer everyNum = Integer.valueOf(chargeInvoiceInhouse.getEveryNums());
            for (int j = 0; j<manynum;j++){
				ChargeInvoiceInhouse chargeInvoiceInhouseNew = new ChargeInvoiceInhouse();
				nstartnum = newstartnum;
				newendnum = nstartnum + chargeInvoiceInhouse.getEveryNums()-1;
				String negroup = group.trim() + df.format(nstartnum);
				chargeInvoiceInhouse.setGroupNo(negroup);
				Integer isExits = chargeInvoiceInhouseService.getGroupIsExits(chargeInvoiceInhouse);//查询票据本编号是否已经存在
				if (isExits > 0){
					newstartnum = newstartnum+1;
					continue;
				}
                ChargeInvoiceType ChargeType = chargeInvoiceTypeService.sureMoney(chargeInvoiceInhouse.getTypeNum());
				if (null != ChargeType){
				    if ("1".equals(ChargeType.getIsFixed())){
                        money= ChargeType.getMaxMoney();
                    }
                }
				money = money *everyNum;
                BigDecimal moneyBig = new BigDecimal(money);
                BigDecimal eyeryNumBig = new BigDecimal(everyNum);
                chargeInvoiceInhouseNew.setMoney(moneyBig.multiply(eyeryNumBig).doubleValue());
                chargeInvoiceInhouseNew.setGroupNo(negroup);
				chargeInvoiceInhouseNew.setWord(chargeInvoiceInhouse.getWord());
				chargeInvoiceInhouseNew.setTypeName(chargeInvoiceType.getName());
				chargeInvoiceInhouseNew.setStartNum(df.format(nstartnum));
				chargeInvoiceInhouseNew.setEndNum(df.format(newendnum));
				chargeInvoiceInhouseNew.setInDate(chargeInvoiceInhouse.getInDate());
				chargeInvoiceInhouseNew.setGroupNum(chargeInvoiceInhouse.getGroupNum());
				chargeInvoiceInhouseNew.setRemarks(chargeInvoiceInhouse.getRemarks());
				chargeInvoiceInhouseNew.setMany(chargeInvoiceInhouse.getMany());
				chargeInvoiceInhouseNew.setEveryNums(chargeInvoiceInhouse.getEveryNums());
				chargeInvoiceInhouseNew.setTypeNum(chargeInvoiceInhouse.getTypeNum());

				chargeInvoiceInhouseService.saveba(chargeInvoiceInhouseNew);
				newstartnum = newendnum + 1;
			}
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	  *  编辑
	 * @param chargeInvoiceInhouse
	 * @return
	 */
	@AutoLog(value = "票据入库-编辑")
	@ApiOperation(value="票据入库-编辑", notes="票据入库-编辑")
	@PutMapping(value = "/edit")
	public Result<ChargeInvoiceInhouse> edit(@RequestBody ChargeInvoiceInhouse chargeInvoiceInhouse) {
		Result<ChargeInvoiceInhouse> result = new Result<ChargeInvoiceInhouse>();
		ChargeInvoiceInhouse chargeInvoiceInhouseEntity = chargeInvoiceInhouseService.getById(chargeInvoiceInhouse.getId());
		if(chargeInvoiceInhouseEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = chargeInvoiceInhouseService.updateById(chargeInvoiceInhouse);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "票据入库-通过id删除")
	@ApiOperation(value="票据入库-通过id删除", notes="票据入库-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			chargeInvoiceInhouseService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "票据入库-批量删除")
	@ApiOperation(value="票据入库-批量删除", notes="票据入库-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<ChargeInvoiceInhouse> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ChargeInvoiceInhouse> result = new Result<ChargeInvoiceInhouse>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.chargeInvoiceInhouseService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "票据入库-通过id查询")
	@ApiOperation(value="票据入库-通过id查询", notes="票据入库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ChargeInvoiceInhouse> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ChargeInvoiceInhouse> result = new Result<ChargeInvoiceInhouse>();
		ChargeInvoiceInhouse chargeInvoiceInhouse = chargeInvoiceInhouseService.getById(id);
		if(chargeInvoiceInhouse==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(chargeInvoiceInhouse);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<ChargeInvoiceInhouse> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              ChargeInvoiceInhouse chargeInvoiceInhouse = JSON.parseObject(deString, ChargeInvoiceInhouse.class);
              queryWrapper = QueryGenerator.initQueryWrapper(chargeInvoiceInhouse, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<ChargeInvoiceInhouse> pageList = chargeInvoiceInhouseService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "票据入库列表");
      mv.addObject(NormalExcelConstants.CLASS, ChargeInvoiceInhouse.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("票据入库列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ChargeInvoiceInhouse> listChargeInvoiceInhouses = ExcelImportUtil.importExcel(file.getInputStream(), ChargeInvoiceInhouse.class, params);
              chargeInvoiceInhouseService.saveBatch(listChargeInvoiceInhouses);
              return Result.ok("文件导入成功！数据行数:" + listChargeInvoiceInhouses.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

	 /**
	  *   票据入库
	  * @param chargeInvoiceInhouse
	  * @return
	  */
	 @AutoLog(value = "票据入库")
	 @ApiOperation(value="票据入库", notes="票据入库")
	 @PostMapping(value = "/insertInvoices")
	 public Result<String> insertInvoices(@RequestBody ChargeInvoiceInhouse chargeInvoiceInhouse) {
		 Result<String> result = new Result<String>();
		 try {
			 String resul = chargeInvoiceInhouseServiceImpl.insertInvoices(chargeInvoiceInhouse);
			 result.success(resul);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("操作失败");
		 }
		 return result;
	 }

}
